package account

import (
	"context"
	"gozero-demo/user/internal/biz"
	"gozero-demo/user/internal/model"
	"strconv"

	"gozero-demo/user/internal/svc"
	"gozero-demo/user/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	// todo: add your logic here and delete this line
	//1、验证用户名密码
	userModel := model.NewUserModel(l.svcCtx.Mysql)
	user, err := userModel.FindByUsernameAndPassword(l.ctx, req.Username, req.Password)
	if err != nil {
		return nil, biz.DBError
	}
	if user == nil {
		return nil, biz.LoginFail
	}
	//2、生成token
	authConfig := l.svcCtx.Config.AuthConfig
	token, err := biz.GetJwtToken(authConfig.AccessSecret, authConfig.Expire, user.Id)
	if err != nil {
		return nil, biz.TokenGenFail
	}
	//3、将token存入redis
	err = l.svcCtx.Redis.SetexCtx(l.ctx, "token:"+strconv.FormatInt(user.Id, 10), token, int(authConfig.Expire))
	if err != nil {
		return nil, biz.RedisFail
	}
	resp = &types.LoginResp{Token: token}
	return
}
